package com.ict.ms.trackPlayBack.service.redis.impl;

import com.ict.ms.trackPlayBack.facade.redis.dao.IUserTestDao;
import com.ict.ms.trackPlayBack.facade.redis.pojo.UserTest;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.Serializable;

@Repository
public class UserTestDaoImpl implements IUserTestDao {
    @Resource
    private RedisTemplate<Serializable, Serializable> redisTemplate;

    @Override
    public void save(final UserTest userTest) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection)
                    throws DataAccessException {
                connection.set(
                        redisTemplate.getStringSerializer().serialize(
                                "userTest.uid." + userTest.getUid()),
                        redisTemplate.getStringSerializer().serialize(
                                userTest.getAddress()));

                return null;
            }
        });
    }

    @Override
    public UserTest read(final String uid) {
        return redisTemplate.execute(new RedisCallback<UserTest>() {
            @Override
            public UserTest doInRedis(RedisConnection connection)
                    throws DataAccessException {
                byte[] key = redisTemplate.getStringSerializer().serialize(
                        "userTest.uid." + uid);
                if (connection.exists(key)) {
                    byte[] value = connection.get(key);
                    String address = redisTemplate.getStringSerializer()
                            .deserialize(value);

                    UserTest userTest = new UserTest();
                    userTest.setAddress(address);
                    userTest.setUid(uid);

                    return userTest;
                }
                return null;
            }
        });
    }

    @Override
    public void delete(final String uid) {
        redisTemplate.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) {
                connection.del(redisTemplate.getStringSerializer().serialize(
                        "userTest.uid." + uid));
                return null;
            }
        });
    }
}